package com.ler.yrmall.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ler.yrmall.enums.BasicStatusEnum;
import com.ler.yrmall.product.entity.AttrEntity;
import com.ler.yrmall.product.entity.SpuAttrValueEntity;
import com.ler.yrmall.product.form.SpuForm;
import com.ler.yrmall.product.mapper.ProductAttrValueMapper;
import com.ler.yrmall.product.service.AttrService;
import com.ler.yrmall.product.service.SpuAttrValueService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author leron
 */
@Service
public class SpuAttrValueServiceImpl extends ServiceImpl<ProductAttrValueMapper, SpuAttrValueEntity> implements SpuAttrValueService {

    @Resource
    private AttrService attrService;

    @Override
    public List<SpuAttrValueEntity> listBySpuId(Long spuId) {
        return this.list(Wrappers.<SpuAttrValueEntity>lambdaQuery().eq(SpuAttrValueEntity::getSpuId,spuId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchSpuBaseAttrs(List<SpuForm.BaseAttrs> baseAttrs, Long spuId) {
        this.remove(Wrappers.<SpuAttrValueEntity>lambdaQuery().eq(SpuAttrValueEntity::getSpuId,spuId));
        List<SpuAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            SpuAttrValueEntity entity = new SpuAttrValueEntity();
            entity.setAttrId(item.getId());
            AttrEntity attrEntity = attrService.getById(item.getId());
            entity.setAttrName(attrEntity.getName());
            entity.setSpuId(spuId);
            entity.setAttrValue(item.getAttrValues());
            entity.setQuickShow(item.getQuickShow());
            return entity;
        }).filter(item -> !item.getAttrValue().isEmpty()).collect(Collectors.toList());
        this.saveBatch(productAttrValueEntities);
    }

    @Override
    public List<SpuAttrValueEntity> getQuickShowAttr(List<Long> spuIds) {
        List<SpuAttrValueEntity> list = this.list(Wrappers.<SpuAttrValueEntity>lambdaQuery()
                .in(SpuAttrValueEntity::getSpuId, spuIds)
                .eq(SpuAttrValueEntity::getQuickShow, BasicStatusEnum.SystemEnableStatus.ENABLED.getCode()));
        return list.stream().map(item -> {
            SpuAttrValueEntity target = new SpuAttrValueEntity();
            BeanUtils.copyProperties(item, target);
            return target;
        }).collect(Collectors.toList());
    }

    @Override
    public void deleteBySpuId(long id) {
        this.remove(Wrappers.<SpuAttrValueEntity>lambdaQuery().eq(SpuAttrValueEntity::getSpuId,id));
    }
}